import { ref, onUnmounted } from 'vue'

// 创建一个Web Worker实例
const createWorker = (workerScript) => {
  const blob = new Blob(['(' + workerScript.toString() + ')()'], { type: 'text/javascript' })
  const url = window.URL.createObjectURL(blob)
  return new Worker(url)
}

function useWebWorker(workerScript) {
  const worker = ref(createWorker(workerScript))
  const message = ref(null)
  const error = ref(null)
  worker.value.onmessage = (e) => {
    message.value = e.data
    error.value = null
  }
  worker.value.onerror = (e) => {
    message.value = null
    error.value = e
  }
  const postMessage = (msg) => worker.value.postMessage(msg)
  const onMessage = (msg) => worker.value.onmessage(msg)
  onUnmounted(() => worker.value.terminate())
  return { postMessage, onMessage, message, error }
}
export default useWebWorker
